<?php

	class node {
		var $id;
		var $name;
		var $type;
		var $completed;
		var $children = array();

		function __construct( $obj ) {
			$this->id = $obj->id;
			$this->name = $obj->name;
			$this->type = "node";
			$this->completed = $obj->completed;
		}

		function prepare() {
			global $objList, $showCompleted;
			$nodeObjs = array();
			foreach( $objList as $obj ) {
				if ( $obj->parentID == $this->id ) {
					$nodeObjs[] = new node($obj);
				}
			}
			foreach( $nodeObjs as $nodeObj ) {
				/* TEST IF COMPLETED NODES ARE DESIRED FOR DISPLAY */

				if ( $nodeObj->completed == 0 || $showCompleted ) {
					$nodeObj->prepare();
					$this->children[] = $nodeObj;
				}
			}
			if ( $this->id == "0" ) $this->id = "root";
		}
	}

	include( "bootstrap.php" );
	
	if ( !isset($_REQUEST["action"]) ) die("No action specified");
	$action = $_REQUEST["action"];
	
	$data = array();

	// *** Add Node action
	if ( $action == "addNode" ) {
		$name = $_POST["name"];
		$desc = $_POST["desc"];
		$name = mysql_real_escape_string($name);
		$desc = mysql_real_escape_string($desc);
		$projectid = $_POST["projectid"];
		$parentid = $_POST["parentid"];
		$time = time();
		$result = query("INSERT INTO ".T_NODES." (projectID,parentID,name,description,createdOn,updatedOn) VALUES ('{$projectid}','{$parentid}','{$name}','{$desc}','{$time}','{$time}')");
		dieSuccess( "Task successfully created" );	
	}
	
	// *** Edit Node action
	if ( $action == "editNode" ) {
		$nodeid = $_POST["nodeid"];
		$nodename = $_POST["nodename"];
		$nodename = mysql_real_escape_string($nodename);
		$time = time();
		$result = query("UPDATE ".T_NODES." SET name='{$nodename}', updatedOn={$time} WHERE id='{$nodeid}'");
		dieSuccess( "Task successfully updated" );
	}

	// *** Delete Node action
	if ( $action == "deleteNode" ) {
		$projectid = $_POST["projectid"];
		$taskid = $_POST["taskid"];
		$childOption = $_POST["childoption"];

		if ( empty($taskid) ) dieError( "Invalid task specified" );

		// Query for deleting orphaned nodes (will need to run until num of affected rows = 0)
		// SELECT t1.id FROM nodes t1 LEFT JOIN nodes t2 ON t2.id=t1.parentID WHERE t2.id is NULL AND t1.parentID != 0;

		if ( $childOption == 0 ) {
			// Delete all child nodes
			$result = query("DELETE FROM ".T_NODES." WHERE id={$taskid}");
			$affected = 1;
			while ( $affected > 0 ) {
				$ids = array();
				$result = query("SELECT t1.id FROM ".T_NODES." t1 LEFT JOIN ".T_NODES." t2 ON t2.id=t1.parentID WHERE t2.id is NULL AND t1.parentID != 0");
				if ( mysql_num_rows($result) == 0 ) $affected = 0;
				else {
					while( $row = mysql_fetch_row($result) ) $ids[] = $row[0];
					$result = query("DELETE FROM ".T_NODES." WHERE id IN (".implode(",", $ids).")");
					// TODO: Delete all 'comments' records for deleted task records
					$affected = mysql_affected_rows();
				}
			}
		} else if ( $childOption == 1 ) {
			// Move orphaned nodes to this nodes parent
			$result = query("SELECT parentID FROM ".T_NODES." WHERE id={$taskid}");
			$row = mysql_fetch_row($result);
			$parentid = $row[0];
			$result = query("DELETE FROM ".T_NODES." WHERE id={$taskid}");
			// TODO: Delete all 'comments' records for deleted task record
			$result = query("UPDATE ".T_NODES." SET parentID={$parentid} WHERE parentID={$taskid}");
		}

		dieSuccess( "Task successfully deleted" );
	}

	// *** Get Node (extended) action
	if ( $action == "getNode" ) {
		$nodeid = $_REQUEST["nodeid"];
		$result = query("SELECT * FROM ".T_NODES." WHERE id='{$nodeid}'");
		if ( mysql_num_rows($result) == 0 ) dieError( "Failed to fech specified node");
		$obj = mysql_fetch_object($result);
		
		$json = array();
		
		$result = query("SELECT * FROM ".T_COMMENTS." WHERE nodeID='{$nodeid}' ORDER BY createdOn ASC");
		if ( mysql_num_rows($result) > 0 ) {
			$comments = array();
			while ( $row = mysql_fetch_object($result) ) {
				$row->createdOn = date("F jS, Y @ g:ia", $row->createdOn );
				$comments[] = $row;
			}
			$json["comments"] = $comments;
		}
		
		// createdOn, updatedOn, completedOn
		$obj->createdOn = date("F jS, Y @ g:ia", $obj->createdOn);
		if ( !empty($obj->updatedOn) ) $obj->updatedOn = date("F jS, Y @ g:ia", $obj->updatedOn);
		if ( !empty($obj->completedOn) ) $obj->completedOn = date("F jS, Y @ g:ia", $obj->completedOn);
		
		$json["result"] = 1;
		$json["node"] = $obj;
		die( json_encode($json) );
	}

	// *** Get Project Nodes action
	if ( $action == "getProjectNodes" ) {
		$projectid = $_GET["projectid"];
		if ( isset($_REQUEST["completed"]) ) $showCompleted = $_REQUEST["completed"]; else $showCompleted = 0;
		$result = query("SELECT * FROM ".T_NODES." WHERE projectID={$projectid} ORDER BY parentID ASC");
		$objList = array();
		while ( $obj = mysql_fetch_object($result) ) $objList[] = $obj;
	
		$obj = new stdClass();
		$obj->id = "0";
		$obj->name = "Project";
		$obj->completed = 0;
		$root = new node( $obj );
		$root->prepare();
		
		$json = array( "identifier" => "id", "label" => "name", "items" => array());
		$json["items"][] = $root;
		
		$json = json_encode($json);
		
		die( $json );
		//$json = json_decode($json);
		//echo "<pre>";
		//echo print_r($json,tr);
		//echo "</pre>";
	}

?>
